import Vue from "vue";
import VueRouter from "vue-router";
import routes from './routes'
import store from '@/store'

Vue.use(VueRouter);

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        //第二种情况：外部在使用push方法的时候没有传递成功与失败的回调函数
        originPush.call(this, location, () => { }, () => { });
    }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
    (resolve && reject) ? originReplace.call(this, location, resolve, reject) : originReplace.call(this, location, () => { }, () => { });
}

let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})

router.beforeEach((to, from, next) => {
    let token = store.state.user.token
    if (token) {
        if (to.path == "/login") {
            next('/')
        } else {
            next()
        }
    } else {
        next()
    }
})


export default router